<?php
namespace app\shop\controller\goods\self;

use app\common\model\shop\CategoryModel;
use app\common\model\shop\PlatformModel;
use app\common\model\shop\self\SelfGoodsAttributeModel;
use app\common\model\shop\self\SelfGoodsCategoryModel;
use app\common\model\shop\self\SelfGoodsImageModel;
use app\common\model\shop\self\SelfGoodsModel;
use app\common\model\shop\self\SelfGoodsPushMsgModel;
use app\common\model\shop\self\SelfGoodsSkuModel;
use app\common\model\shop\ShopsModel;
use app\common\service\shop\SyncGoodService;
use think\admin\Controller;
use think\admin\extend\DataExtend;
use think\admin\helper\QueryHelper;
use think\admin\model\SystemUser;
use think\App;
use think\facade\Db;
use think\facade\Validate;

/**
 * 自有平台商品管理
 * @Description
 * @package app\shop\controller\goods\self
 * @author wangqinghui
 * @date 2025-01-13 09:09
 */
class Goods extends Controller
{

    public $platform_id = 0;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $platform_info = PlatformModel::where('code', PlatformModel::SELF_CODE)->find();
        $this->platform_id = $platform_info['id'] ?? 0;
    }


    /**
     * 商品列表
     * @auth true
     * @menu true
     * @Description
     * @author wangqinghui
     * @date 2025-01-11 17:35
     * @return void
     */
    public function index()
    {
        SelfGoodsModel::mQuery()->layTable(function () {
            $this->title = lang('商品管理');
            // 订单来源
            $this->from_arr = SelfGoodsModel::from_arr();
            // 用户列表
            $user_list = SystemUser::getUserList($this->account_id, SystemUser::getNoTeacherUserType());
            $this->system_user = array_column($user_list, 'nickname', 'id');
            // 店铺列表
            $map = [
                ['is_deleted',  '=', 0]
            ];
            if(!empty($this->account_id)){
                $map[] = ['account_id', '=', $this->account_id];
            }
            $this->shop_list = ShopsModel::mk()->where($map)->column('id,name');
            // 推送状态
            $this->push_status_arr = SelfGoodsModel::pushStatusArr();

        }, function (QueryHelper $query) {

            $query->with(['userName','updateName','skuList' => function($sku) {
                $sku->field('id,title,goods_id,attribute_titles,sale_price,price,stock,goods_nu');
            }]);

            $query->where('is_deleted', 0);

            $query->like('title,source_url#collect_url')->equal('account_id,from_type#from,user_id,update_user_id,spu_code,shop_id,push_status')->dateBetween('create_at,update_at');
            $query->order('id desc');
        });
    }

    protected function _index_page_filter(&$data)
    {
        // 获取店铺信息
        $shop_ids = array_column($data, 'shop_id');
        $shop_data = [];
        if(!empty($shop_ids)){
            $shop_data = ShopsModel::mk()->whereIn('id', $shop_ids)->column('id,name', 'id');
        }
        // 获取分类信息
        $shop_category_ids = array_column($data, 'shop_category_id');
        $shop_category_data = [];
        if(!empty($shop_category_ids)){
            $shop_category_data = CategoryModel::mk()->whereIn('id', $shop_category_ids)->column('id,name', 'id');
        }
        // 推送状态集合
        $push_status_arr = SelfGoodsModel::pushStatusArr();
        foreach ($data as &$v) {
            // 来源
            $v['from_text'] = SelfGoodsModel::from_arr()[$v['from_type']];
            // 店铺名称
            $v['shop_name'] = !empty($shop_data[$v['shop_id']]['name']) ? $shop_data[$v['shop_id']]['name'] : '';
            // 分类名称
            $v['shop_category_name'] = !empty($shop_category_data[$v['shop_category_id']]['name']) ? $shop_category_data[$v['shop_category_id']]['name'] : '';
            // 推送状态
            $v['push_status_text'] = $push_status_arr[$v['push_status']];
        }
    }

    /**
     * 添加商品
     * @Description
     * @auth true
     * @author wangqinghui
     * @date 2025-01-13 09:33
     * @return void
     */
    public function add()
    {
        SelfGoodsModel::mForm();
    }


    /**
     * 编辑商品
     * @Description
     * @auth true
     * @author wangqinghui
     * @date 2025-01-13 09:33
     * @return void
     */
    public function edit()
    {
        SelfGoodsModel::mForm();
    }

    protected function _form_filter(&$data)
    {
        if($this->request->isPost()){

            // 处理复选框元素
            $data['video_open'] = !empty($data['video_open']) ? 1 : 0;
            $data['is_sub'] = !empty($data['is_sub']) ? 1 : 0;
            $data['is_limit'] = !empty($data['is_limit']) ? 1 : 0;
            $data['vip_product'] = !empty($data['vip_product']) ? 1 : 0;
            $data['presale'] = !empty($data['presale']) ? 1 : 0;
            $data['is_show'] = !empty($data['is_show']) ? 1 : 0;

            if(empty($data['category_id'])){
                $this->error('请选择分类');
            }

            $rule = [
                'account_id|'.lang('公司')   =>  'require|integer|>:0',
                'shop_id|'.lang('店铺')   =>  'require|integer|>:0',
                'title|'.lang('标题')   =>  'require|max:200',
                'mode_type|'.lang('库存类型')   =>  'require|in:0,1',
                'unit_name|'.lang('商品单位')    =>  'require|max:10',
                'is_show|'.lang('商品状态')   =>  'require|in:0,1',
                'keyword|'.lang('关键词')    =>  'max:100',
                'video_open|'.lang('添加视频')   =>  'require|in:0,1',
                'video_link|'.lang('视频地址')   =>  'require|max:255',
                'postage|'.lang('运费')    =>  'float|between:0,1000000000',
                'ficti|'.lang('已售数量')    =>  'integer|between:0,1000000000',
                'give_integral|'.lang('购买送积分')   =>  'integer|between:0,1000000000',
                'is_sub|'.lang('是否单独分佣')   =>  'require|in:0,1',
                'is_limit|'.lang('是否限购')     =>  'require|in:0,1',
                'limit_type|'.lang('限购类型')   =>  'require|in:1,2',
                'limit_num|'.lang('限购数量')    =>  'require|integer|between:1,1000000000',
                'vip_product|'.lang('会员专属')   =>  'require|in:0,1',
                'presale|'.lang('预售商品')     =>  'require|in:0,1',
                'presale_time|'.lang('预售时间')  =>  'require',
                'presale_day|'.lang('发货时间')  =>  'require|integer|between:0,1000000000',
                'spu_code|SPU'  =>  'require|max:100',
                'source_url|'.lang('货源URL')    =>  'max:255',
                'shop_category_id|'.lang('ERP分类')  =>  'integer|>:0',
                'goods_images|'.lang('产品图片') =>  'require',
                'short_desc|'.lang('简单描述')   =>  'max:65530',
                'long_desc|'.lang('详细描述')    =>  'max:65530',
            ];
            $validate = Validate::rule($rule);
            $only = ['account_id','shop_id','title','mode_type','unit_name','is_show','keyword','video_open','postage','ficti','give_integral','is_sub'
            ,'is_limit','vip_product','presale','spu_code','source_url','shop_category_id','goods_images','short_desc','long_desc'];
            if (!$validate->only($only)->check($data)) {
                $this->error($validate->getError());
            }

            $goods_img_arr = !empty($data['goods_images']) ? explode('|', $data['goods_images']) : [];
            $goods_info = [
                'account_id'    => $data['account_id'] ?? 0,
                'spu_code'      => $data['spu_code'] ?? '',
                'title'         => $data['title'] ?? '',
                'keyword'       =>  $data['keyword'] ?? '',
                'category_id'   =>  $data['category_id'] ?? '',
                'shop_id'       => $data['shop_id'] ?? 0,
                'shop_category_id'  => $data['shop_category_id'] ?? 0,
                'mode_type'     => $data['mode_type'] ?? 0,
                'unit_name'     => $data['unit_name'],
                'main_pic'      => $goods_img_arr[0] ?? '',
                'short_desc'    => $data['short_desc'] ?? '',
                'long_desc'     => $data['long_desc'] ?? '',
                'mode_type'     =>  $data['mode_type'],
                'source_url'    => $data['source_url'] ?? '',
                'postage'       => $data['postage'] ?? 0,
                'is_limit'      => $data['is_limit'],
                'vip_product'   =>  $data['vip_product'],
                'is_show'       => $data['is_show'] ?? 0,
                'presale'       => $data['presale'],
                'video_open'    => $data['video_open'],
                'ficti'         =>  $data['ficti'] ?? 0,
                'give_integral' => $data['give_integral'] ?? 0,
                'is_sub'        => $data['is_sub'],
            ];
            // 是否限购
            if(!empty($goods_info['is_limit'])){
                if (!$validate->only(['limit_type','limit_num'])->check($data)) {
                    $this->error($validate->getError());
                }
                $goods_info['limit_type']   = $data['limit_type'];
                $goods_info['limit_num']   = $data['limit_num'];
            }
            // 是否预售
            if(!empty($goods_info['presale'])){
                if (!$validate->only(['presale_time','presale_day'])->check($data)) {
                    $this->error($validate->getError());
                }
                $goods_info['presale_time'] = $data['presale_time'];
                $goods_info['presale_day'] = $data['presale_day'] ?? 0;
            }
            // 是否开启视频
            if(!empty($goods_info['video_open'])){
                if (!$validate->only(['video_link'])->check($data)) {
                    $this->error($validate->getError());
                }
                $goods_info['video_link']   = $data['video_link'];
            }

            // 校验sku信息
            $sku_rule = [
                'goods_nu|'.lang('产品编号')  => 'require|max:100',
                'price|'.lang('售价')   => 'require|float|between:0.01,10000000',
                'sale_price|'.lang('原价') => 'require|float|between:0.01,10000000',
                'stock|'.lang('库存')       =>  'require|integer|between:1,1000000',
                'length|'.lang('长')         =>  'require|float|between:0.01,1000000',
                'width|'.lang('宽')          =>  'require|float|between:0.01,1000000',
                'height|'.lang('高')         =>  'require|float|between:0.01,1000000',
                'weight|'.lang('重量')       =>  'require|float|between:0.01,1000000',
                'image|'.lang('图片')         =>  'require|max:255',
                'cost|'.lang('成本')   => 'require|float|between:0.01,10000000',
            ];
            if($data['mode_type'] == 1){
                if(empty($data['skus'])){
                    $this->error('请至少添加一条SKU信息');
                }
                // 获取sku是否存在
                $code_arr = array_column($data['skus'], 'goods_nu');
                $map = [
                    ['goods_nu', 'in', $code_arr],
                ];
                if(!empty($data['id'])){
                    $map[] = ['goods_id', '<>', $data['id']];
                }
                $exist_sku_data = SelfGoodsSkuModel::mk()->where($map)->column('id', 'goods_nu');
                $unique_sku = [];
                $validate = Validate::rule($sku_rule);
                foreach ($data['skus'] as $key => $sku_info) {
                    if (!$validate->check($sku_info)) {
                        $this->error($key.$validate->getError());
                    }
                    if(isset($unique_sku[$sku_info['goods_nu']])){
                        $this->error($sku_info['goods_nu'].'SKU与上面重复了');
                    }
                    if(!empty($exist_sku_data[$sku_info['goods_nu']])){
                        $this->error($sku_info['goods_nu'].'SKU已存在');
                    }
                    $unique_sku[$sku_info['goods_nu']] = 1;
                }
            }else{
                $data['sku']['image'] = $goods_img_arr[0] ?? '';
                $validate = Validate::rule($sku_rule);
                if (!$validate->check($data['sku'])) {
                    $this->error($validate->getError());
                }
                // 校验sku是否唯一
                $map = [
                    ['goods_nu', '=', $data['sku']['goods_nu']]
                ];
                if(!empty($data['id'])){
                    $map[] = ['goods_id', '<>', $data['id']];
                }
                $count = SelfGoodsSkuModel::mk()->where($map)->count();
                if($count > 0){
                    $this->error($data['sku']['goods_nu'].'SKU已存在');
                }
            }

            // 商品推荐
            $recommend = [];
            $recommend_arr = SelfGoodsModel::getRecommendArr();
            foreach ($recommend_arr as $key => $val){
                if(!empty($data[$key])){
                    $recommend[] = $key;
                }
            }
            if(!empty($recommend)){
                $goods_info['recommend'] = json_encode($recommend);
            }

            if(!empty($data['id'])){
                $goods_info['update_user_id']   = $this->adminUser['id'] ?? 0;
                $action = '编辑';
            }else{
                $goods_info['user_id']  = $this->adminUser['id'] ?? 0;
                $goods_info['from_type'] = 2;
                $action = '添加';
            }

            // 获取sku信息
            $old_sku_data = [];
            if(!empty($data['id'])){
                $map = [
                    ['goods_id', '=', $data['id']]
                ];
                $old_sku_data = SelfGoodsSkuModel::mk()->where($map)->column('id', 'goods_nu');
            }

            // 启动事务
            Db::startTrans();
            try {
                // 添加/编辑商品
                if(!empty($data['id'])){
                    SelfGoodsModel::mk()->where('id', '=', $data['id'])->update($goods_info);
                    $goods_id = $data['id'];
                }else{
                    $goods_id = SelfGoodsModel::mk()->insertGetId($goods_info);
                }

                // 商品图片
                if(!empty($goods_img_arr)){
                    SelfGoodsImageModel::mk()->where('goods_id', '=', $goods_id)->delete();
                    $add_image_arr = [];
                    foreach ($goods_img_arr as $img_key => $img_val) {
                        $add_image_arr[] = [
                            'goods_id'  => $goods_id,
                            'image'       => $img_val,
                        ];
                    }
                    SelfGoodsImageModel::mk()->insertAll($add_image_arr);
                }

                // 商品属性
                $spec_data = [];
                if(!empty($data['specData'])){
                    SelfGoodsAttributeModel::mk()->where('goods_id', '=', $goods_id)->delete();
                    $add_goods_attr = [];
                    foreach ($data['specData'] as $spec_key => $spec_val) {
                        if(!empty($spec_val['child'])){
                            foreach ($spec_val['child'] as $key => $value) {
                                $add_goods_attr[] = [
                                    'goods_id'  => $goods_id,
                                    'key_name'  => $spec_val['title'],
                                    'value_name'    => $value['title'],
                                    'checked'   => !empty($value['checked']) ? 1 : 0,
                                ];
                            }
                        }
                    }
                    if(!empty($add_goods_attr)){
                        SelfGoodsAttributeModel::mk()->insertAll($add_goods_attr);
                    }
                }

                // 商品SKU
                $goods_skus = [];
                if($data['mode_type'] == 1) {
                    // 处理SKU
                    if(!empty($data['skus']) && !empty($data['specData'])) {
                        // 获取删除的sku
                        $delete_sku_ids = array_diff_key($old_sku_data, array_column($data['skus'], 'goods_nu', 'goods_nu'));
                        if(!empty($delete_sku_ids)){
                            SelfGoodsSkuModel::mk()->where('id', 'in', $delete_sku_ids)->delete();
                        }
                        // 获取属性值
                        $spec_data = SelfGoodsAttributeModel::mq()->where('goods_id', '=', $goods_id)->column('id', 'value_name');
                        foreach ($data['skus'] as $k => $v) {
                            $attribute_arr = explode(',', $k);
                            $attribute_ids_arr = [];
                            foreach ($attribute_arr as $key => $value) {
                                $attribute_ids_arr[] = !empty($spec_data[$value]) ? $spec_data[$value] : 0;
                            }
                            $attribute_ids = implode(',',$attribute_ids_arr);
                            $temp_sku = [
                                'goods_id' => $goods_id,
                                'goods_nu' => $v['goods_nu'],
                                'image' => $v['image'],
                                'price' => $v['price'],
                                'sale_price' => $v['sale_price'],
                                'length' => $v['length'],
                                'width' => $v['width'],
                                'height' => $v['height'],
                                'weight' => $v['weight'],
                                'stock' => $v['stock'],
                                'volume' => round($v['length'] * $v['width'] * $v['height'],3),
                                'attribute_ids' => $attribute_ids,
                                'attribute_titles'  =>  $k,
                                'cost'  =>  $v['cost'],
                            ];
                            if(!empty($old_sku_data[$v['goods_nu']])){
                                $edit_id = $old_sku_data[$v['goods_nu']];
                                SelfGoodsSkuModel::mk()->where('id', '=', $edit_id)->update($temp_sku);
                            }else{
                                $temp_sku['origional_attribute_titles'] = $k;
                                $goods_skus[] = $temp_sku;
                            } 
                        }
                    }
                } else {
                    $temp_sku = [
                        'goods_id' => $goods_id,
                        'goods_nu' => $data['sku']['goods_nu'],
                        'price' => $data['sku']['price'] ?? 0,
                        'sale_price' => $data['sku']['sale_price'] ?? 0,
                        'length' => $data['sku']['length'] ?? 0,
                        'width' => $data['sku']['width'] ?? 0,
                        'height' => $data['sku']['height'] ?? 0,
                        'weight' => $data['sku']['weight'] ?? 0,
                        'stock' => $data['sku']['stock'] ?? 0,
                        'volume' => round($data['sku']['length'] * $data['sku']['width'] * $data['sku']['height'],3),
                        'image'  =>  $data['sku']['image'],
                        'cost'  =>  $data['sku']['cost'],
                    ];
                    $edit_id = current($old_sku_data);
                    if(!empty($edit_id)){
                        SelfGoodsSkuModel::mk()->where('id', '=', $edit_id)->update($temp_sku);
                    }else{
                        $goods_skus[] = $temp_sku;
                    }
                }
                if($goods_skus) {
                    // 添加sku表
                    SelfGoodsSkuModel::mk()->insertAll($goods_skus);
                }

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($action.'商品失败:'.$e->getMessage());
            }
            $this->success($action.'商品成功');
        }else{
            // 获取系统分类
            $category_where = [
                ['status', '=', 1],
            ];
            $shop_category_list = CategoryModel::mk()->where($category_where)->order('level')->field('name title,id,pid,path')->select()->toArray();
            $this->shop_category_list = CategoryModel::categoryTree($shop_category_list);

            // 获取店铺列表
            $this->shop_list = ShopsModel::mk()->where(['user_id' => $this->adminUser['id'], 'is_deleted' => 0, 'platform_id' => $this->platform_id])->column('name', 'id');

            $specDataTree = $goods_skus_data = [];
            if(!empty($data['id'])) {
                // 获取sku
                if($data['mode_type'] == 0) { // 单品
                    $this->sku_info = SelfGoodsSkuModel::mk()->where(['goods_id' => $data['id']])->find();
                } else { // 多品
                    //  商品规格
                    $specData = SelfGoodsAttributeModel::mk()->where(['goods_id' => $data['id']])->select()->toArray();
                    if(!empty($specData)){
                        foreach($specData as $key => $val) {
                            $specDataTree[$val['key_name']]['id'] = $val['key_name'];
                            $specDataTree[$val['key_name']]['title'] = $val['key_name'];
                            $specDataTree[$val['key_name']]['child'][] = [
                                'id' => $val['value_name'],
                                'title' => $val['value_name'],
                                'checked' => $val['checked'],
                            ];
                        }
                    }
                    $specDataTree = array_values($specDataTree);
                    // skus todo
                    $goods_skus = SelfGoodsSkuModel::mk()->where(['goods_id' => $data['id']])->select()->toArray();
                    $goods_skus_data = [];
                    foreach ($goods_skus as $v){
                        $goods_skus_data["skus[" . $v['attribute_titles'] . "][image]"] = $v['image'];
                        $goods_skus_data["skus[" . $v['attribute_titles'] . "][goods_nu]"] = $v['goods_nu'];
                        $goods_skus_data["skus[" . $v['attribute_titles'] . "][price]"] = $v['price'];
                        $goods_skus_data["skus[" . $v['attribute_titles'] . "][sale_price]"] = $v['sale_price'];
                        $goods_skus_data["skus[" . $v['attribute_titles'] . "][length]"] = $v['length'];
                        $goods_skus_data["skus[" . $v['attribute_titles'] . "][width]"] = $v['width'];
                        $goods_skus_data["skus[" . $v['attribute_titles'] . "][height]"] = $v['height'];
                        $goods_skus_data["skus[" . $v['attribute_titles'] . "][weight]"] = $v['weight'];
                        $goods_skus_data["skus[" . $v['attribute_titles'] . "][stock]"] = $v['stock'];
                        $goods_skus_data["skus[" . $v['attribute_titles'] . "][cost]"] = $v['cost'];
                    }
                }
                $this->specDataTree = json_encode($specDataTree);
                $this->goods_skus_data = json_encode($goods_skus_data ?? []);
                //  商品规格
                $GoodsImages = SelfGoodsImageModel::mk()->where(['goods_id' => $data['id']])->column('image');
                $this->goods_images = implode('|',$GoodsImages);
                $data['recommend'] = !empty($data['recommend']) ? json_decode($data['recommend'], 1) : [];
            }

            $this->shop_account = !empty($data['account_id']) ? $data['account_id'] : $this->account_id;

            // 商品推荐
            $this->goods_recommend = SelfGoodsModel::getRecommendArr();
        }
    }

    /**
     * 获取商品SPU
     * @Description
     * @author wangqinghui
     * @date 2025-01-10 17:51
     * @return void
     */
    public function createSPU()
    {
        // 获取
        $spu_code = SelfGoodsModel::mk()->createSPU();
        $this->success('', (string)$spu_code);
    }

    /**
     * 删除商品
     * @Description
     * @auth true
     * @author wangqinghui
     * @date 2025-01-13 09:34
     * @return void
     */
    public function delete()
    {
        $id = $this->request->param('id', 0);

        $info = SelfGoodsModel::mq()->find($id);
        if(!$info) {
            $this->error('产品信息错误');
        }
        try {
            $result = SelfGoodsModel::mq()->where(['id' => $id])->update(['is_deleted' => 1]);
            if(!$result){
                throw new \Exception(lang('删除失败'));
            }
        } catch (\Exception $e) {
            $this->error(lang('删除失败'));
        }
        $this->success(lang('删除成功'));
    }

    /**
     * 推送商品
     * @Description
     * @auth true
     * @author wangqinghui
     * @date 2025-01-13 09:34
     * @return void
     */
    public function pushGoods ()
    {
        $ids = $this->request->post('ids', '');
        if(empty($ids)){
            $this->error('请选择需要推送的商品');
        }
        $ids_arr = explode(',', $ids);

        $sync_goods_service = new SyncGoodService();

        $ret = $sync_goods_service->pushGoods($ids_arr, 'self');
        if(empty($ret['code']) || ($ret['code'] != 1)){
            $this->error($ret['msg']);
        }

        $this->success('推送成功');
    }

    /**
     * 获取分类列表
     * @return void
     */
    public function getCategoryList()
    {
        $account_id = (int)$this->request->post('account_id', 0);
        $map = [
            ['account_id',  '=', $account_id],
            ['is_show',  '=', 1]
        ];
        $field = 'pid,cate_id,name';
        $cate_list = SelfGoodsCategoryModel::mk()->field($field)->where($map)->order('sort', 'desc')->select()->toArray();
        $list = DataExtend::arr2tree($cate_list, 'cate_id', 'pid', 'children');
        $this->success(lang('分类列表'), $list);
    }

    /**
     * 获取推送错误日志
     * @Description
     * @author wangqinghui
     * @date 2025-01-16 10:06
     * @return void
     */
    public function pushErrorList()
    {
        $goods_id = (int)$this->request->post('id', 0);
        if(empty($goods_id) || ($goods_id <= 0)){
            $this->error('商品ID参数错误');
        }
        $page = (int)$this->request->post('page', 1);
        $limit = (int)$this->request->post('limit', 10);
        $map = [
            ['goods_id', '=', $goods_id]
        ];
        $total = SelfGoodsPushMsgModel::mk()->where($map)->count();
        $list = SelfGoodsPushMsgModel::mk()->where($map)->page($page, $limit)->order('id', 'desc')->select()->toArray();
        if(!empty($list)){
            $goods_ids = array_column($list, 'goods_id');
            $goods_data = SelfGoodsModel::mk()->whereIn('id', $goods_ids)->column('id,spu_code', 'id');
            $push_type = SelfGoodsPushMsgModel::getPushTypeArr();
            foreach($list as $key => $item){
                $goods_id = $item['goods_id'] ?? 0;
                $list[$key]['spu_code'] = !empty($goods_data[$goods_id]['spu_code']) ? $goods_data[$goods_id]['spu_code'] : '';
                $list[$key]['type_text'] = !empty($push_type[$item['type']]) ? $push_type[$item['type']] : '';
            }
        }
        $this->success('获取成功', ['item' => $list, 'total' => $total], 0);
    }

    /**
     * 同步库存
     * @Description
     * @auth true
     * @author wangqinghui
     * @date 2025-01-13 09:35
     * @return void
     */
    public function syncStock()
    {
        $ids = $this->request->post('ids', '');
        if(empty($ids)){
            $this->error('请选择需要同步库存的商品');
        }

        $ids_arr = explode(',', $ids);
        $sync_goods_service = new SyncGoodService();
        $ret = $sync_goods_service->pushGoodsStock($ids_arr, 'self');

        if(empty($ret['code']) || ($ret['code'] != 1)){
            $this->error($ret['msg']);
        }

        $this->success('同步库存成功');
    }

    /**
     * 设置商品库存
     * @Description
     * @auth true
     * @author wangqinghui
     * @date 2025-01-21 11:51
     * @return void
     */
    public function setInventory()
    {
        if($this->request->isPost()){
            $sku_stock = $this->request->post('sku_data', '');
            if(empty($sku_stock)){
                $this->error('sku库存无数据');
            }
            $sku_data_arr = json_decode($sku_stock, 1);
            if(empty($sku_data_arr)){
                $this->error('sku库存无数据');
            }
            $rule = [
                'id|SKUID'    =>  'require|integer|>:0',
                'goods_nu|商品SKU'  =>  'require',
                'stock|库存'    =>  'require|number|between:0,1000000',
            ];
            $validate = Validate::rule($rule);
            $update_data = [];
            foreach($sku_data_arr as $sku_info){
                if(!$validate->check($sku_info)){
                    $this->error(($sku_info['goods_nu'] ?? '').$validate->getError());
                }
            }

            // 更新库存
            // 启动事务
            Db::startTrans();
            try {
                foreach($sku_data_arr as $sku_info){
                    $update_data = [
                        'stock'     =>  $sku_info['stock'],
                    ];
                    SelfGoodsSkuModel::mk()->where('id', $sku_info['id'])->update($update_data);
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error('库存更新失败:'.$e->getMessage());
            }
            $this->success('库存更新成功');
        }else{
            $goods_id = (int)$this->request->get('id', 0);
            if(empty($goods_id) || ($goods_id <= 0)){
                $this->error('商品ID参数错误');
            }
            $this->fetch('', ['goods_id' => $goods_id]);
        }
    }

    /**
     * 获取商品库存
     * @Description
     * @author wangqinghui
     * @date 2025-01-21 11:50
     * @return void
     */
    public function getSkuStock()
    {
        $goods_id = (int)$this->request->post('goods_id', 0);
        if(empty($goods_id) || ($goods_id <= 0)){
            $this->error('商品ID参数错误');
        }
        $map = [
            ['goods_id',    'in',   $goods_id],
        ];
        $field = 'id,goods_id,goods_nu,stock,attribute_titles';
        $sku_stock_list = SelfGoodsSkuModel::mk()->field($field)->where($map)->select()->toArray();
        $this->success('获取库存成功', ['item' => $sku_stock_list, 'total' => count($sku_stock_list)], 0);
    }
}